package com.squirrels.server.service;

import com.squirrels.server.entity.Room;
import dev.morphia.Datastore;
import io.netty.channel.ChannelHandlerContext;
import lombok.Data;

import java.net.InetSocketAddress;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 创建者: FlyingSquirrels
 * 创建时间: 2024/8/21 17:55
 * 描述: 房间服务类
 */
@Data
public class RoomService {

    private static RoomService roomService;

    // 房间列表
    private ConcurrentHashMap<String,Room> roomMap;

    // 数据库操作服务
    private UserService userService;

    private RoomService(){}

    // 获取房间服务
    public static synchronized RoomService getService(){
        if (null == RoomService.roomService) {
            RoomService.roomService = new RoomService();
            RoomService.roomService.setRoomMap(new ConcurrentHashMap<>());
        }
        return RoomService.roomService;
    }

    /**
     * 创建房间返回 房间id
     * 使用用户uid作为房间id
     * @return
     */
    public String CreateRoom(String uid, InetSocketAddress sender,String name){
        roomMap.put(uid,new Room(uid,sender,UserService.operation(),name));
        return  uid;
    }

    /**
     * 获取房间信息
     * @param roomId
     * @param uid
     * @return
     */
    public Room getRoomUserById(String roomId){
        return roomMap.get(roomId);
    }

    /**
     * 查找空闲房间id
     * @return
     */
    public String getNotFullRoomId(){
        Set<Map.Entry<String, Room>> entries = roomMap.entrySet();
        for (Map.Entry<String, Room> entry : entries) {
            if (entry.getValue().isNotFull()){
                return entry.getKey();
            }
        }
        return null;
    }
}
